package com.springboot.nacos.config.client;


import small.common.core.util.StringUtil;
import com.small.nacos.api.config.ConfigService;
import com.small.nacos.api.exception.NacosException;
import com.springboot.nacos.config.NacosPropertySourceRepository;
import com.springboot.nacos.config.parse.NacosDataParserHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertySource;

import java.util.Collections;
import java.util.Date;
import java.util.List;

public class NacosPropertySourceBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(NacosPropertySourceBuilder.class);

    private ConfigService configService;

    private long timeout;

    public NacosPropertySourceBuilder(ConfigService configService, long timeout) {
        this.configService = configService;
        this.timeout = timeout;
    }

    public NacosPropertySource build(String dataId, String group, String fileExtension, boolean isRefreshable) {
        List<PropertySource<?>> propertySources = loadNacosData(dataId, group,
                fileExtension);
        NacosPropertySource nacosPropertySource = new NacosPropertySource(propertySources, group, dataId, new Date(), isRefreshable);
        NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource);
        return nacosPropertySource;
    }

    private List<PropertySource<?>> loadNacosData(String dataId, String group, String fileExtension) {

        String data = null;
        try {
            data = configService.getConfig(dataId, group, timeout);
            if (StringUtil.isEmpty(data)) {
                return Collections.emptyList();
            }
            //解析数据源
            return NacosDataParserHandler.getInstance().parseNacosData(dataId, data,
                    fileExtension);
        } catch (NacosException e) {
            LOGGER.error("get data from Nacos error,dataId:{} ", dataId, e);
        } catch (Exception e) {
            LOGGER.error("parse data from Nacos error,dataId:{},data:{}", dataId, data, e);
        }
        return Collections.emptyList();
    }
}
